package tk.xboot.boot.conf;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class TpeMonitor implements Runnable {

    private ThreadPoolExecutor executor;
    private static final int DELAY = 3000;
    private volatile boolean run = true;
    private int tps = 1000;

    /**
     * 构造方法
     *
     * @param executor 线程执行器
     */
    public TpeMonitor(ThreadPoolExecutor executor) {
        this.executor = executor;
    }


    /**
     * 构造方法
     *
     * @param executor 线程执行器
     * @param tps      多少秒采样一次
     */
    public TpeMonitor(ThreadPoolExecutor executor, int tps) {
        if (tps > 1) {
            this.tps *= tps ;
        }
        this.executor = executor;
    }


    public void shutdown() {
        this.run = false;
    }


    /**
     * Get the generate info of the thread pool.
     *
     * isShutdown() return true when shutdown() method is called.
     *
     * isTerminated() return true when shutdown() method is called and all committed task is completed.
     *
     */
    @Override
    public void run() {
        try {
            Thread.sleep(DELAY);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        while (run) {
            long activeCnt = executor.getActiveCount();
            long taskCnt = executor.getTaskCount();
            long queueSize = taskCnt - activeCnt;
            log.info("A/C:[{}/{}] Active:{}, Task:{}, Queue:{}, Completed:{}",
                            executor.getPoolSize(),
                            executor.getCorePoolSize(),
                            activeCnt,
                            taskCnt,
                            queueSize,
                            this.executor.getCompletedTaskCount());

            /*log.info("[monitor] [{}/{}] Active:{}, Task:{}, Queue:{}, Completed:{}, Shutdown:{}, Terminated:{}",
                    executor.getPoolSize(),
                    executor.getCorePoolSize(),
                    activeCnt,
                    taskCnt,
                    queueSize,
                    this.executor.getCompletedTaskCount(),
                    this.executor.isShutdown(),
                    this.executor.isTerminated());*/

            //log.info(executor.toString());

            try {
                Thread.sleep(tps);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

    }
}
